﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NerdDinner.Web.Models.Data;

namespace NerdDinner.Web.Models.Repository
{
    public class DinnerRepository : IDinnerRepository
    {
        private NerdDinnerDataContext db = new NerdDinnerDataContext();


        #region IDinnerRepository Members

        public IQueryable<Dinner> FindAllDinners()
        {
            return db.Dinners;
        }

        public IQueryable<Dinner> FindByLocation( float latitude, float longitude, int distance )
        {
            var dinners = from dinner in FindUpcomingDinners()
                          join i in db.NearestDinners( latitude, longitude, distance )
                          on dinner.DinnerId equals i.DinnerId
                          select dinner;

            return dinners;
        }

        public IQueryable<Dinner> FindUpcomingDinners()
        {
            var upComingDinners = from dinner in db.Dinners
                                  where dinner.EventDate > DateTime.Now
                                  orderby dinner.EventDate
                                  select dinner;
            return upComingDinners;
        }

        public Dinner GetDinner( int id )
        {
            return db.Dinners.SingleOrDefault( d => d.DinnerId == id );
        }

        public void Add( Dinner dinner )
        {
            db.Dinners.InsertOnSubmit( dinner );
        }

        public void Delete( Dinner dinner )
        {
            db.RSVPs.DeleteAllOnSubmit( dinner.RSVPs );
            db.Dinners.DeleteOnSubmit( dinner );
        }

        public void Save()
        {
            db.SubmitChanges();
        }

        #endregion
    }
}